﻿using System;
using System.Collections.Generic;

namespace RuTracker.Interface.Dropbox
{
    [Serializable]
    public class StorageFolder : IStorageItem
    {
        private readonly List<IStorageItem> _children;

        public StorageFolder(string name, IStorageItem parent)
        {
            _children = new List<IStorageItem>();
            Parent = parent;
            Name = name;
        }
        
        public IStorageItem Parent { get; private set; }
        public string Name { get; private set; }

        public string FullName
        {
            get { return ToString(); }
        }

        public IEnumerable<IStorageItem> Children
        {
            get { return _children; }
        }

        public StorageFolder AddFolder(string name)
        {
            var result = new StorageFolder(name, this);
            _children.Add(result);
            return result;
        }

        public StorageFile AddFile(string name)
        {
            var result = new StorageFile(name, this);
            _children.Add(result);
            return result;
        }

        public override string ToString()
        {
            string parentFullName = Parent == null ? string.Empty : Parent.ToString();
            if (Parent == null)
            {
                return string.Format("/{0}", Name);
            }
            return string.Format("{0}{1}/", parentFullName, Name);
        }

        public bool IsEmpty 
        {
            get { return _children.Count == 0; }
        }

        public IStorageItem GetChild(string path)
        {
            return GetChild(path, Children);
        }

        private IStorageItem GetChild(string path, IEnumerable<IStorageItem> children)
        {
            IStorageItem result = null;

            foreach (IStorageItem item in children)
            {
                StorageFolder folder = item as StorageFolder;
                if (folder != null)
                    result = GetChild(path, folder.Children);

                if (item.FullName == path)
                    result = item;

                if (result != null)
                    break;
            }

            return result;
        }
    }
}
